#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import requests, json, sys, re

# 初始化参数
default_engine='bing'
default_target_lang='en'

LANGS = ['en', 'tw', 'de'] # 目标语言参数
user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0'
Engines = {
    'BING': 'https://cn.bing.com/ttranslatev3'
        }

class BaseTranslator:
    def __init__():
        pass
    def init_request():
        pass
    def request(self,data = None, *args, **kwargs):
        if 'headers' in kwargs:
            headers = kwargs['headers']
        else:
            headers={}
            headers['User-Agent'] = user_agent
        if 'method' in kwargs:
            if kwargs['method'] == 'GET':
                res = requests.get(self._url, params = self.get_params(), headers = headers)
        else:
            res = requests.post(self._url, data=self.get_params().encode('utf-8'), headers=headers)
        self._res = res

    def result(self):
        # 格式化输出结果
        pass
    def get_params():
        pass

    def translate(self, text, *args, **kwargs):
        pass

class BingTranslator(BaseTranslator):
    html_url='https://cn.bing.com/translator'
    def __init__(self):
        self._url        = Engines['BING']
        self._isVertical = 1

    def init_request(self):
        # 初始化实例
        headers={}
        headers['User-Agent'] = user_agent
        html_res = requests.get(self.html_url)
        html_text = html_res.text
        # 正则表达式解析
        ig_reg = 'IG:"\w+"'
        m = re.search(ig_reg, html_text)
        if m:
            group = m.group()
            self._IG = group[4:-1]
        iid_reg = 'data-iid="\w+\.\w+"'
        m = re.search(iid_reg, html_text)
        if m:
            group = m.group()
            self._IID = group[10:-1]

    def get_params(self):
        return ('fromLang=auto-detect&to=%s&text=%s' % (self._to_lang, self._text))

    def result(self):
        if self._res is not None:
            res  = self._res.json()
            if 'statusCode' in res and res['statusCode'] == 400:
                return None
            json = res[0]
            format_json= {
                    'text': self._text,
                    'source_lang': json['detectedLanguage']['language'],
                    'target_lang': json['translations'][0]['to'],
                    'translate_reault': json['translations'][0]['text']
                    }
            return format_json
        return None

    def translate(self, text, target_lang = default_target_lang):
        self._text = text
        self._to_lang = target_lang
        headers = {
                'content-type': 'application/x-www-form-urlencoded',
                'user-agent':'Mozilla/5.0 (X11; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0'
                }
        if self._IG is not None and self._IID is not None:
            self._url = ('%s?isVertical=%d&IG=%s&IID=%s' % (Engines['BING'], self._isVertical, self._IG, self._IID))
        self.request(headers = headers)

bingTranslator = BingTranslator()
translator = bingTranslator
translator.init_request()

def init_engine(engine):
    if engine == 'bing':
        translator = bingTranslator
        translator.init_request()

def translate(text, target_lang = 'en'):
    res = translator.translate(text, target_lang)
    if res is not None:
        return translator.result()

__all__ = ['translate', 'translator', 'default_target_lang', 'default_engine','init_engine']
